import Decimal from 'decimal.js';

// 设置全局精度（默认20位）
Decimal.set({ precision: 30 });

/**
 * 精确加法
 */
export const preciseAdd = (...nums: (number | string | Decimal)[]): Decimal => {
    return nums.reduce(
        (acc: Decimal, num) => acc.add(new Decimal(num)),
        new Decimal(0)
    );
};

/**
 * 精确减法
 */
export const preciseSubtract = (a: number | string | Decimal, ...nums: (number | string | Decimal)[]): Decimal => {
    const init = new Decimal(a);
    return nums.reduce(
        (acc: Decimal, num) => acc.sub(new Decimal(num)),
        init
    );
};

/**
 * 精确乘法
 */
export const preciseMultiply = (...nums: (number | string | Decimal)[]): Decimal => {
    return nums.reduce(
        (acc: Decimal, num) => acc.mul(new Decimal(num)),
        new Decimal(1)
    );
};

/**
 * 精确除法
 */
export const preciseDivide = (a: number | string | Decimal, ...nums: (number | string | Decimal)[]): Decimal => {
    const init = new Decimal(a);
    return nums.reduce(
        (acc: Decimal, num) => acc.div(new Decimal(num)),
        init
    );
};

/**
 * 格式化结果（保留小数位/返回数字）
 */
export const formatResult = (
    value: Decimal,
    options: {
        decimals?: number;
        returnNumber?: boolean
    } = {}
): number | string => {
    const { decimals = 2, returnNumber = false } = options;
    const fixedValue = value.toFixed(decimals);

    return returnNumber
        ? parseFloat(fixedValue)
        : fixedValue;
};

// 可选：导出 Decimal 类型以便在组件中使用
export type { Decimal };
